﻿Imports System
Imports System.Drawing
Imports System.Windows.Forms

<System.ComponentModel.ToolboxItem(False)>
Friend Class AutoCompleteMenuHost
    Inherits ToolStripDropDown

    Public ReadOnly Menu As AutoCompleteMenu
    Private _listView As IAutoCompleteListView

    Public Property Host() As ToolStripControlHost
    Public Property ListView() As IAutoCompleteListView
        Get
            Return _listView
        End Get
        Set(value As IAutoCompleteListView)
            If _listView IsNot Nothing Then
                RemoveHandler CType(_listView, Control).LostFocus, New EventHandler(AddressOf ListView_LostFocus)
            End If

            If value Is Nothing Then
                _listView = New AutoCompleteListView()
            Else
                If Not (TypeOf value Is Control) Then
                    Throw New Exception("ListView must be derived from Control class")
                End If
                _listView = value
            End If

            Host = New ToolStripControlHost(CType(ListView, Control))
            Host.Margin = New Padding(2, 2, 2, 2)
            Host.Padding = Padding.Empty
            Host.AutoSize = False
            Host.AutoToolTip = False

            CType(ListView, Control).MaximumSize = Menu.MaximumSize
            CType(ListView, Control).Size = Menu.MaximumSize
            AddHandler CType(ListView, Control).LostFocus, New EventHandler(AddressOf ListView_LostFocus)

            CalcSize()
            MyBase.Items.Clear()
            MyBase.Items.Add(Host)
            CType(ListView, Control).Parent = Me
        End Set
    End Property
    Public Overrides Property RightToLeft() As RightToLeft
        Get
            Return MyBase.RightToLeft
        End Get
        Set(value As RightToLeft)
            MyBase.RightToLeft = value
            CType(ListView, Control).RightToLeft = value
        End Set
    End Property

    Public Sub New(menu As AutoCompleteMenu)
        AutoClose = False
        AutoSize = False
        Margin = Padding.Empty
        Padding = Padding.Empty

        Me.Menu = menu
        ListView = New AutoCompleteListView()
    End Sub

    Protected Overrides Sub OnPaintBackground(e As PaintEventArgs)
        Using brush = New SolidBrush(_listView.Colors.BackColor)
            e.Graphics.FillRectangle(brush, e.ClipRectangle)
        End Using
    End Sub

    Friend Sub CalcSize()
        Host.Size = CType(ListView, Control).Size
        Size = New Size(CType(ListView, Control).Size.Width + 4, CType(ListView, Control).Size.Height + 4)
    End Sub

    Protected Overrides Sub OnLostFocus(e As EventArgs)
        MyBase.OnLostFocus(e)
        If Not CType(ListView, Control).Focused Then
            Close()
        End If
    End Sub

    Sub ListView_LostFocus(sender As Object, e As EventArgs)
        If Not Focused Then
            Close()
        End If
    End Sub
End Class